<template>
    <div>
        <!-- 面包屑导航区 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片视图区 -->
        <el-card class="box-card">
            <!-- 栅格布局 -->
            <el-row :gutter="30">
                <el-col :span="9"> <!-- 第一列 搜索-->
                    <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear='getUserList()'>
                        <el-button slot="append" icon="el-icon-search" @click="getUserList()"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4"> <!-- 第二列 按钮-->
                    <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
                </el-col>
            </el-row>
            <!-- 用户列表区 -->
            <el-table :data="userList" style="width: 100%" border stripe>
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column prop="username" label="姓名"></el-table-column>
                <el-table-column prop="email" label="邮箱"></el-table-column>
                <el-table-column prop="mobile" label="电话"></el-table-column>
                <el-table-column prop="role_name" label="角色"></el-table-column>
                <el-table-column label="状态">
                    <!-- 作用域插槽，用v-slot='slotProps'拿到作用域里的数据 -->
                    <!-- .row是内置的属性，可以拿到当前行的数据，老版本写法是slot-scope="scope"再scope.row -->
                    <template v-slot:default="slotProps">
                        <!-- {{slotProps.row}} -->
                        <el-switch 
                            v-model="slotProps.row.mg_state" 
                            active-color="#13ce66" 
                            inactive-color="#ff4949"
                            @change='userStateChange(slotProps.row.id)'>
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="190px">
                    <template v-slot='slotProps'>
                        <!-- 修改按钮 -->
                        <el-tooltip effect="dark" content="修改" placement="top" :enterable='false'>
                            <el-button type="primary" icon="el-icon-edit" size="mini" 
                            @click="showEditDialog(slotProps.row.id)" ></el-button>
                        </el-tooltip>
                        <!-- 删除按钮 -->
                        <el-tooltip effect="dark" content="删除" placement="top" :enterable='false'>
                            <el-button type="danger" icon="el-icon-delete" size="mini" 
                            @click="removeUserByID(slotProps.row.id)"></el-button>
                        </el-tooltip>
                        <!-- 分配角色按钮 -->
                        <el-tooltip effect="dark" content="修改角色" placement="top" :enterable='false'>
                            <el-button type="warning" icon="el-icon-setting" size="mini"
                            @click="setRoleDialog(slotProps.row)"></el-button>
                        </el-tooltip>
                    </template> 
                </el-table-column>  
            </el-table>
            <!-- 分页功能 -->
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum"
                :page-sizes="[1, 2, 5, 10]"
                :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </el-card>
        <!-- 添加用户的对话框 -->
        <el-dialog
            title="添加用户"
            :visible.sync="addDialogVisible"
            width="50%"
            @close='addDialogClose()'>
            <!-- 内容主体区 -->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addForm.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="addForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <!-- 底部确认/取消按钮 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser()">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 编辑用户的对话框 -->
        <el-dialog
            title="编辑用户信息"
            :visible.sync="editDialogVisible"
            width="50%"
            @close='editDialogClose()'>
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
                <el-form-item label="用户名"> <!--不需要prop校验规则（禁用的）-->
                    <el-input v-model="editForm.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="editForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUser()">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 分配角色的对话框 -->
        <el-dialog
            title="编辑用户信息"
            :visible.sync="setRoleDialogVisible"
            width="50%"
            @close='setRoleDialogClosed()'>
            <div>
                <p>当前的用户：{{setRoleForm.username}}</p>
                <p>当前的角色：{{setRoleForm.role_name}}</p>
                <p>分配角色：
                    <el-select v-model="selectedRoleId" placeholder="请选择">
                        <el-option
                        v-for="i in setRoleList"
                        :key="i.id"
                        :label="i.roleName"
                        :value="i.id">
                        </el-option>
                    </el-select>
                </p>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="setRole()">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name:'Users',
    data() {
        // 自定义添加用户时,邮箱和手机的校验规则
        let checkEmail=(rule,value,callback)=>{
            // 正则表达式校验，用到.test()方法
            const regEmail=/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
            if(regEmail.test(value)){
                callback() //格式合法
            }else{
                callback(new Error('邮箱格式不正确'))
            }
        }
        let checkMobile=(rule,value,callback)=>{
            const regMobile=/^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
            if(regMobile.test(value)){
                callback()
            }else{
                callback(new Error('手机格式不正确'))
            }
        }

        return {
            // 获取用户列表的参数
            queryInfo:{
                query:'',
                pagenum:1, //当前页码数
                pagesize:2 //当前每页显示多少条数据
            },
            // 从用户接口拿到的数据保存在此
            userList:[],
            total:0,
            addDialogVisible:false,
            editDialogVisible:false,
            // 添加用户的表单数据
            addForm:{
                username:'',
                password:'',
                email:'',
                mobile:''
            },
            // 添加用户的表单的验证规则
            addFormRules:{
                username:[
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                password:[
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
                ],
                email:[
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator : checkEmail, trigger : 'blur' }
                ],
                mobile:[
                    { required: true, message: '请输入手机', trigger: 'blur' },
                    { validator : checkMobile, trigger : 'blur' }
                ]
            },
            // 编辑用户时的表单数据
            editForm:{},
            // 编辑用户的表单的验证规则
            editFormRules:{
                email:[
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator : checkEmail, trigger : 'blur' }
                ],
                mobile:[
                    { required: true, message: '请输入手机', trigger: 'blur' },
                    { validator : checkMobile, trigger : 'blur' }
                ]
            },
            // 分配角色对话框的显示和隐藏
            setRoleDialogVisible:false,
            // 分配角色的表单数据
            setRoleForm:[],
            setRoleList:[],
            selectedRoleId:''
        }
    },
    methods:{
        async getUserList(){
            const {data:result}=await this.$http.get('users',{params:this.queryInfo})
            if(result.meta.status!==200){
                return this.$message.error('获取用户列表失败')
            }else{
                this.userList=result.data.users
                this.total=result.data.total
            }
        },
        handleSizeChange(val){ //监听pagesize改变
            // console.log(`每页 ${val} 条`)
            this.queryInfo.pagesize=val
            // 因为页码、每页显示数发生变化了，所以得重新调用API接口，因为这些都是请求时候的参数
            this.getUserList()
        },
        handleCurrentChange(val){ //监听当前页码变化
            // console.log(`当前页: ${val}`)
            this.queryInfo.pagenum=val
            this.getUserList()
        },
        // 新增用户
        async userStateChange(userinfo){
            const {data:result}=await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
            if(result.meta.status!==200){
                this.$message.error('修改用户状态失败')
                userinfo.mg_state=!userinfo.mg_state //页面上开关取反
            }else{
                this.$message.success('修改用户状态成功')
            }
        },
        // Dialog 关闭的回调
        addDialogClose(){
            this.$refs['addFormRef'].resetFields()
        },
        // 点击确定，添加用户   
        addUser(){
            this.$refs['addFormRef'].validate(async (valid)=>{
                if(valid){
                    // 如果验证通过，发起网络请求
                    const {data:result}=await this.$http.post('users',this.addForm)
                    if(result.meta.status!==201){
                        this.$message.error('添加用户失败')
                    }else{
                        this.addDialogVisible=false //隐藏对话框
                        this.getUserList() //刷新用户列表
                        this.$message.success('添加用户成功')
                    }
                }
            })
        },
        // 编辑用户信息
        async showEditDialog(id){
            const {data:result}=await this.$http.get('users/'+id)
            if(result.meta.status!==200){
                this.$message.error('查询用户信息失败')
            }else{
                this.editForm=result.data
                this.editDialogVisible=true
            }
        },
        // 
        editDialogClose(){
            this.$refs['editFormRef'].resetFields()
        },
        // 点击确定，编辑用户  
        editUser(){
            this.$refs['editFormRef'].validate(async (valid)=>{
                if(valid){
                    // 如果验证通过，发起网络请求
                    const {data:result}=await this.$http.put('users/'+this.editForm.id, {email:this.editForm.email, mobile:this.editForm.mobile})
                    if(result.meta.status!==200){
                        this.$message.error('更新用户信息失败')
                    }else{
                        this.editDialogVisible=false //隐藏对话框
                        this.getUserList() //刷新用户列表
                        this.$message.success('更新用户信息成功')
                    }
                }
            })
        },
        // 删除用户
        async removeUserByID(id){
            const confirmResult=await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch((err)=>{return err})
            // 如果确认删除则返回的是字符串'confirm'，如果取消删除则返回字符串'cancel'
            if (confirmResult!=='confirm'){
                this.$message.info('已取消删除')
            }else{
                const {data:result}=await this.$http.delete('users/'+id)
                if(result.meta.status!==200){
                    this.$message.error('删除用户失败')
                }else{
                    this.getUserList()
                    this.$message.success('删除成功')
                }
            }
        },
        // 分配角色的对话框
        async setRoleDialog(userInfo){
            this.setRoleForm=userinfo
            const {data:result}=await this.$http.get('roles')
            if(result.meta.status!==200){
                this.$message.error('获取角色列表失败')
            }else{
                this.setRoleList=result.data
                this.setRoleDialogVisible=true
                this.$message.success('获取角色列表成功')
            }
        },
        // 点击确定，分配角色
        async setRole(){
            if(!this.selectedRoleId){
                this.$message.error('你没选要分配的角色')
            }else{
                const {data:result}=await this.$http.put(`users/${this.setRoleForm.id}/role`,{rid:this.selectedRoleId})
                if(result.meta.status!==200){
                    this.$message.error('更新用户角色失败')
                }else{
                    this.getUserList()
                    this.setRoleDialogVisible=false
                    this.$message.success('更新用户角色成功')
                }
            }
        },
        setRoleDialogClosed(){
            this.selectedRoleId=''
            this.setRoleForm=[]
        }
    },
    created(){
        this.getUserList()
    }
}
</script>

<style lang='less' scoped>
    .el-card{
        box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2) !important;
    }
</style>